﻿using IDAL;
using Model;
using NHibernate;
using System.Collections.Generic;

namespace SqlDALLibrary
{
    public class NoticeDal : INoticeDAL
    {
        private static EntityControl control;

        static NoticeDal()
        {
            control = EntityControl.CreateEntityControl("Model");
        }

        public void saveNotice(Notice notcie)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(notcie);
                tx.Commit();
            }
            session.Close();
        }

        public void updateNotice(Notice notcie)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Update(notcie);
                tx.Commit();
            }
            session.Close();
        }

        public Notice getNotice(int id)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Notice notice = session
                .CreateQuery("from Notice n where n.id=:id")
                .SetInt32("id", id)
                .UniqueResult<Notice>();
            session.Close();
            return notice;
        }

        public IList<Notice> getNotice(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Notice> noticeList = session
                .CreateQuery("from Notice n where n.toWho=:toWho")
                .SetParameter("toWho", user)
                .List<Notice>();
            session.Close();
            return noticeList;
        }

        public IList<Notice> getNotice()
        {
            return control.getSession()
                .CreateQuery("from Notice")
                .List<Notice>();
        }

        public IList<Notice> getNotice(User user, int status)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Notice> noticeList = session
                .CreateQuery("from Notice n where n.toWho=:toWho and status=:status")
                .SetParameter("toWho", user)
                .SetInt32("status", status)
                .List<Notice>();
            session.Close();
            return noticeList;
        }

    }
}
